
library(gtools)
library(combinat)

bandt_pompe_method = function(data, D=4){
  #creating vector frequency
  frequency_vector = list()
  permutations = permn(0:(D-1))
  for(i in permutations){
    frequency_vector[[paste(i,collapse="")]] = 0
  }
  
  possitions = data.frame(ids=0:(D-1),values=rep(0,D))
  
  for(i in 1:(dim(data)[1]-D+1)){
   possitions$values = data[i:(i+D-1),]
   sorted = possitions[mixedorder(possitions$values),]
   ordinal_pattern = paste(sorted$ids, collapse="")
   frequency_vector[[ordinal_pattern]] = frequency_vector[[ordinal_pattern]] + 1
  }
  
  output = data.frame(patterns = names(frequency_vector), 
                      frequencies = unlist(frequency_vector, use.names=FALSE) , 
                      probabilities = unlist(frequency_vector, use.names=FALSE)/ (dim(data)[1]-D+1))
  
  return(output)
}
  








